package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.UserMapper;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.ScoreChangeEnum;
import com.yupi.springbootinit.service.UserScoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.yupi.springbootinit.constant.UserConstant.USER_LOGIN_STATE;

@Service
@Slf4j
public class UserScoreServiceImpl extends ServiceImpl<UserMapper, User> implements UserScoreService {

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getScoreByUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        User currentUserScore = this.getById(userId);
        if (currentUserScore == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUserScore;
    }

    // 与数据库上次的签到时间比较，判断今日是否已签
    @Override
    public boolean compareTime(Date signInTime) throws ParseException {
        // 以 "年-月-日" 格式输出 ,可参考https://blog.csdn.net/WANGLI123956/article/details/131139869
        String form = String.format("%tF", signInTime);
        System.out.println("上次签到时间："+form);

        Date date = new Date();
        String nowForm = String.format("%tF", date);
        System.out.println("现在的时间："+nowForm);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = df.parse(form);
        Date date2 = df.parse(nowForm);
        // 判断是否是：date1的时间在date2之前，如果是返回true否则返回false
        // 可参考https://blog.csdn.net/MinggeQingchun/article/details/121653740
        return date1.before(date2);
    }

    @Override
    public User getScoreByUserId(Long id) {
        User currentUserScore = this.getById(id);
        if (currentUserScore == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUserScore;
    }

    /**
     * 扣除积分
     * @param userId 用户id
     * @param type 此次操作需要扣除的积分数
     */
    @Override
    public Boolean checkAndDeduct(Long userId, Integer type) {
        User user = this.getById(userId);
        Integer userScore = user.getUserScore();
        if (userScore < type){
            return false;
        }
        userScore -= type;
        user.setUserScore(userScore);
        return this.updateById(user);
    }

    /**
     * 积分回退
     * @param userId 用户id
     * @param type 此次操作需要扣除的积分数
     */
    @Override
    public Boolean sendCompensate(Long userId, Integer type){
        User user = this.getById(userId);
        Integer userScore = user.getUserScore();

        userScore += type;
        user.setUserScore(userScore);
        return this.updateById(user);
    }
}
